﻿using System;
using System.ComponentModel.Composition;
using System.Reflection;
using System.Runtime.CompilerServices;
using log4net;
using Lhn.Ds.Core.Exceptions;
using Lhn.Ds.Core.Service;

namespace Lhn.Ds.Core.Controll
{
    public class LoginModel : BaseModel
    {
        private static readonly ILog Log =
            LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private string _name;

        private string _password;

        [Import] public UserService UserService { get; set; }

        public string Name
        {
            get => _name;
            set
            {
                if (_name == value) return;
                _name = value;
                OnPropertyChanged();
            }
        }

        public string Password
        {
            get => _password;
            set
            {
                if (_password == value) return;
                _password = value;
                OnPropertyChanged();
            }
        }

        private bool _isLoging;

        public bool IsLoging
        {
            get => _isLoging;
            set
            {
                if (_isLoging == value) return;
                _isLoging = value;
                OnPropertyChanged();
            }
        }


        public ReplayCommand LoginCommand => new ReplayCommand(_ =>
        {
            IsLoging = true;
            Dispatch(async () =>
            {
                try
                {
                    var rt = await UserService.Login(Name, Password);
                    DsContext.InstanceData.DispatchAction("//UserLogin");
                }
                catch (Exception e)
                {
                    DsContext.InstanceData.ProccessException(e);
                }
                finally
                {
                    DispatchUI(() => { IsLoging = false; });
                }
            });
        }, () => !(string.IsNullOrWhiteSpace(_name) || string.IsNullOrWhiteSpace(_password)) && !IsLoging);

        protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);
        }
    }
}